import React, { useContext, useState } from 'react';
import { MdArrowRight, MdKeyboardArrowUp } from 'react-icons/md';
import { Tag } from 'antd';
import classNames from 'classnames';

import { testingMap } from '../constants';

import { MenuContext } from './Menu';

const SubMenu = ({
  route,
  pathKey,
  title,
  children,
  className,
  openSubMenus,
  MenuIndex,
  defaultArrowDir = 'up',
}) => {
  const context = useContext(MenuContext);
  const [menuOpen, setMenuOpen] = useState(!!openSubMenus);
  const classes = classNames('menu-item submenu-item', className, {
    active: context.pathKey === pathKey,
    opened: menuOpen,
    'sec-submenu-item': MenuIndex === 2,
  });
  const handleClick = (e) => {
    e.preventDefault();
    setMenuOpen(!menuOpen);
  };

  const renderChildren = () => {
    const subMenuClasses = classNames('submenu', {
      'menu-opened': menuOpen,
    });
    const childrenComponent = React.Children.map(children, (child) => {
      if (
        child.type.displayName === 'MenuItem' ||
        child.type.displayName === 'SubMenu'
      ) {
        return React.cloneElement(child, {
          pathKey: child.props.route?.path,
        });
      }
    });
    return <ul className={subMenuClasses}>{childrenComponent}</ul>;
  };

  return (
    <li key={pathKey} className={classes}>
      <div className="submenu-title" onClick={handleClick}>
        <span className="submenu-title-text">{title}</span>
        <Tag
          size="small"
          className="testing-icon"
          style={{ visibility: route.testing ? 'visible' : 'hidden' }}
        >
          {testingMap[route.testing]}
        </Tag>
        {defaultArrowDir === 'up' ? (
          <MdKeyboardArrowUp size="16" className="arrow-icon" />
        ) : (
          <MdArrowRight size="18" className="arrow-icon" />
        )}
      </div>
      {renderChildren()}
      <div className="submenu-border" />
    </li>
  );
};

SubMenu.displayName = 'SubMenu';
export default SubMenu;
